// pages/shopCar/shopCar.js
const app = getApp();
const util = require("../../utils/util.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    carList: [],
    isNoProduct: false,
    totalPrice: 0,
    isCheckAll: false,
    // istrue: 1,
    shoppingId: [],
    number: [],
    youhuiPrice: 0
  },

  // 点击去逛逛
  toIndex: function(e) {
    wx.reLaunch({
      url: '../index/index',
    })
  },

  // 点击选中商品
  isChoiceProduct: function(e) {
    let that = this
    app.globalData.couponid = 0
    app.globalData.cost = 0
    that.setData({
      totalPrice: 0,
      youhuiPrice:0
      // carList[i].ischoice : true
    })
    let carList = that.data.carList
    let index = e.currentTarget.dataset.index
    for (let i = 0; i < carList.length; i++) {
      if (index == i) {
        carList[i].ischoice = !carList[i].ischoice
        that.setData(that.data)
      }
      if (carList[i].ischoice == true) {
        let totalPrice = that.data.totalPrice
        totalPrice = carList[i].price * carList[i].number + totalPrice
        that.setData({
          totalPrice: totalPrice,
          istrue: true
        })
      } else {
        carList[index].ischoice = !carList[index].ischoice
        that.setData({
          istrue: false
        })
        that.setData(that.data)
        break
      }
    }
    // console.log(that.data.istrue)
    if (that.data.istrue == true) {
      that.setData({
        isCheckAll: true
      })
    } else {
      that.setData({
        isCheckAll: false
      })
    }
    that.setData(that.data)
    that.totalPrice()
    
  },

  /* 点击减号 */
  bindMinus: function(e) {
    
    let that = this
    app.globalData.couponid = 0
    app.globalData.cost = 0
    that.setData({
      totalPrice: 0,
      youhuiPrice: 0
      // carList[i].ischoice : true
    })
    let carList = that.data.carList
    let index = e.currentTarget.dataset.index
    for (let i = 0; i < carList.length; i++) {
      if (index == i) {
        if (carList[i].number > 1) {
          carList[i].number--
            that.setData(that.data)
        }
      }
    }
    that.totalPrice()
  },

  /* 点击加号 */
  bindPlus: function(e) {
    let that = this
    app.globalData.couponid = 0
    app.globalData.cost = 0
    that.setData({
      totalPrice: 0,
      youhuiPrice: 0
      // carList[i].ischoice : true
    })
    let carList = that.data.carList
    let index = e.currentTarget.dataset.index
    for (let i = 0; i < carList.length; i++) {
      if (index == i) {
        carList[i].number++
          that.setData(that.data)
      }
    }
    that.totalPrice()
  },

  /* 输入框事件 */
  bindManual: function(e) {
    let that = this
    app.globalData.couponid = 0
    app.globalData.cost = 0
    that.setData({
      totalPrice: 0,
      youhuiPrice: 0
      // carList[i].ischoice : true
    })
    let carList = that.data.carList
    let index = e.currentTarget.dataset.index
    for (let i = 0; i < carList.length; i++) {
      if (index == i) {
        carList[i].number = e.detail.value
        that.setData(that.data)
      }
    }
    that.totalPrice()
  },

  // 计算总价
  totalPrice: function(e) {
    let that = this
    that.setData({
      totalPrice: 0,
      shoppingId: [],
      number: []
    })
    let carList = that.data.carList
    let discount = app.globalData.cost
    // console.log(discount)
    for (let i = 0; i < carList.length; i++) {
      if (carList[i].ischoice == true) {
        let totalPrice = that.data.totalPrice
        totalPrice = carList[i].price * carList[i].number + totalPrice
        that.setData({
          totalPrice: totalPrice
          // totalPrice: totalPrice - discount
        })
      }
    }
  },

  // 删除购物车商品
  deleteProduct: function(e) {
    let that = this
    app.globalData.couponid = 0
    app.globalData.cost = 0
    that.setData({
      totalPrice: 0,
      youhuiPrice: 0
      // carList[i].ischoice : true
    })
    wx.showModal({
      title: '确认删除',
      content: '您确认从购物车删除该商品吗',
      confirmText: "确认",
      cancelText: "取消",
      success: function(res) {
        // console.log(res);
        if (res.confirm) {
          // 发送删除订单请求
          let deleteShoppingProductUrl = app.globalData.baseUrl + "weixin/deleteShoppingProduct"
          let data = {
            shoppingId: e.currentTarget.id
          }
          util.requestLoading(deleteShoppingProductUrl, data, "GET").then(res => {
            // console.log(res)
            // 请求购物车列表
            let shopUrl = app.globalData.baseUrl + "weixin/shoppingList"
            let cid = wx.getStorageSync('cid')
            let data = {
              cid: cid
            }
            util.requestLoading(shopUrl, data, "GET").then(res => {
              // console.log(res)
              that.setData({
                carList: res.data.shoppingList
              })
              // 计算总价
              that.totalPrice()
            })
          })
        }
      }
    })
  },

  // 购物车全选
  isChoiceProductAll: function(e) {
    let that = this
    app.globalData.couponid = 0
    app.globalData.cost = 0
    that.setData({
      totalPrice: 0,
      youhuiPrice: 0
      // carList[i].ischoice : true
    })
    let carList = that.data.carList
    if (that.data.isCheckAll == false) {
      that.data.isCheckAll = true
      for (let i = 0; i < carList.length; i++) {
        carList[i].ischoice = true
      }
      that.setData(that.data)
    } else {
      that.data.isCheckAll = false
      for (let i = 0; i < carList.length; i++) {
        carList[i].ischoice = false
      }
      that.setData(that.data)
    }
    // 计算总价
    that.totalPrice()
  },

  // 选择优惠券
  choiceCoupon: function(e) {
    let that = this
    let couponId = app.globalData.couponid
    if (that.data.totalPrice == 0){
      wx.showModal({
        content: '请先选择您需要的商品后选择可用优惠券',
        showCancel: false
      })
    } else {
      wx.navigateTo({
        url: 'coupon/coupon?price=' + that.data.totalPrice + '&couponId=' + couponId
      })
    }
  },

  // 点击结算
  shoppingCartSettlement: function(e) {
    // for()
    let that = this
    let couponId = app.globalData.couponid
    let discount = app.globalData.cost
    // console.log(couponId, discount)
    let carList = that.data.carList
    let shoppingId = that.data.shoppingId
    let number = that.data.number
    for (let i = 0; i < carList.length; i++) {
      if (carList[i].ischoice == true) {
        shoppingId.push(carList[i].shoppingId)
        number.push(carList[i].number)
      }
    }
    that.setData({
      shoppingId: shoppingId,
      number: number
    })
    // console.log(shoppingId,number)
    
    // 发送结算请求
    let commitToOrderUrl = app.globalData.baseUrl + "weixin/commitToOrder"
    let cid = wx.getStorageSync('cid')
    let data = {
      cid: cid,
      shoppingId: that.data.shoppingId,
      discount: discount,
      couponId: couponId,
      number: that.data.number
    }
    let productName
    util.requestLoading(commitToOrderUrl, data, "GET").then(res => {
      console.log(res)
      that.setData({
        orderId: res.data.orderId
      })
      if (res.data.status == 0) {
        wx.showLoading()
        // 发送支付请求
        let payUrl = app.globalData.baseUrl + "weixin/pay"
        let openid = wx.getStorageSync('openId')
        let data = {
          openid: openid,
          orderId: that.data.orderId,
          money: that.data.totalPrice
        }
        util.requestLoading(payUrl, data, "GET").then(res => {
          // console.log(res)
          if (res.statusCode == 200) {
            wx.hideLoading()
            let openId = wx.getStorageSync("openId")
            wx.requestPayment({
              timeStamp: res.data.timeStamp,
              nonceStr: res.data.nonceStr,
              package: res.data.package,
              signType: 'MD5',
              paySign: res.data.paySign,
              success(res) {
                // console.log(res)
                // // 发送成功回调请求
                // let payResultUrl = app.globalData.baseUrl + "weixin/payResult"
                // let data = {
                //   orderId: that.data.orderId,
                //   money: that.data.totalPrice,
                //   status: 0
                // }
                // util.requestLoading(payResultUrl, data, "GET").then(res => {
                //   // console.log(res)
                // })
                wx.showModal({
                  content: '支付成功',
                  showCancel: false,
                  success: function (res) {
                    if (res.confirm) {
                      wx.reLaunch({
                        url: '../../index/index'
                      })
                    }
                  }
                })
              },
              fail(res) {
                // console.log(res)
                // // 发送失败回调请求
                // let payResultUrl = app.globalData.baseUrl + "weixin/payResult"
                // let data = {
                //   orderId: that.data.orderId,
                //   money: that.data.totalPrice,
                //   status: 1
                // }
                // util.requestLoading(payResultUrl, data, "GET").then(res => {
                //   // console.log(res)
                // })
                wx.reLaunch({
                  url: '../index/index'
                })
              }
            })
          }
        })
      }
      // that.setData({
      //   carList: res.data.shoppingList
      // })
      // // 计算总价
      // that.totalPrice()
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // let that = this
    // // 请求购物车列表
    // let shopUrl = app.globalData.baseUrl + "weixin/shoppingList"
    // let cid = wx.getStorageSync('cid')
    // let data = {
    //   cid: cid
    // }
    // util.requestLoading(shopUrl, data, "GET").then(res => {
    //   // console.log(res)
    //   that.setData({
    //     carList: res.data.shoppingList
    //   })
    //   // 计算总价
    //   that.totalPrice()
      
    // })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    app.globalData.cost = 0
    app.globalData.couponid = 0
  },

  onShow: function(){
    let that = this
    // that.setData({
    //   discount : app.globalData.cost,
    //   couponId : app.globalData.couponid
    // })
    let discount = app.globalData.cost
    let couponId = app.globalData.couponid
    if (discount == 0 && couponId == 0) {
      // 请求购物车列表
      let shopUrl = app.globalData.baseUrl + "weixin/shoppingList"
      let cid = wx.getStorageSync('cid')
      let data = {
        cid: cid
      }
      util.requestLoading(shopUrl, data, "GET").then(res => {
        // console.log(res)
        that.setData({
          carList: res.data.shoppingList
        })
        // 计算总价
        that.totalPrice()
        // console.log(this.data.carList)
        // console.log(this.data.carList.length)
        if (this.data.carList.length == 0) {
          this.setData({
            isNoProduct: false
          })
        } else {
          this.setData({
            isNoProduct: true
          })
        }
      })
      let totalPrice = this.data.totalPrice - discount
      this.setData({
        totalPrice: totalPrice,
        isCheckAll: false,
        youhuiPrice: discount
      })
    } else {
      that.totalPrice()
      let totalPrice = this.data.totalPrice - discount
      // console.log(discount)
      if (discount!=0){
        this.setData({
          youhuiPrice: discount
        })
      }
      this.setData({
        totalPrice: totalPrice,
        // isCheckAll: false,
      })
    }
  },
})